import { Context } from 'egg';
import { RESULT_CODE } from '../utils/constants/code';

export default () => {
  return async (ctx: Context, next: () => Promise<any>) => {
    try {
      await next();
    } catch (err: any) {
      // 记录错误日志
      ctx.app.emit('error', err, ctx);

      const status = err.status || RESULT_CODE.FAIL;
      const message = err.message || '服务器内部错误';

      // 统一错误响应格式
      ctx.status = 200;
      ctx.body = {
        code: status,
        message,
        data: null,
        timestamp: new Date().toISOString(),
      };

      // 开发环境下返回错误堆栈
      if (ctx.app.config.env === 'local') {
        ctx.body.stack = err.stack;
      }
    }
  };
};